package user_dao

import (
	"admin-system-go/model/do"
	"admin-system-go/repository"
)

func InsertUser(user *do.User) error {
	tx := repository.GetDb().Begin()
	if err := tx.Create(user).Error; err != nil {
		tx.Rollback()
		return err
	}
	commit := tx.Commit()
	return commit.Error
}

func QueryAllUser() ([]do.User, error) {
	var users []do.User
	err := repository.GetDb().Model(do.User{}).Find(&users).Error
	return users, err
}

func QueryUserByCondition(user do.User) []do.User {
	var users []do.User
	result := repository.GetDb().Where(&user).Find(&users)
	if result.RowsAffected == 0 {
		return []do.User{}
	}
	return users
}

func GetUserById(id uint) *do.User {
	var user = do.User{Uid: id}
	return getUserByCondition(&user)
}

func GetUserByUsername(username string) *do.User {
	var user = do.User{Username: username}
	return getUserByCondition(&user)
}

func getUserByCondition(user *do.User) *do.User {
	tx := repository.GetDb().Where(user).Find(user)
	if tx.RowsAffected == 0 {
		return nil
	}
	return user
}

func UpdateUser(user *do.User) bool {
	result := repository.GetDb().Model(user).Save(user)
	return result.Error == nil
}
